var itemNumId;

if (/id=(\d+)&?/.exec(window.location.href)) {
    itemNumId = /id=(\d+)&?/.exec(window.location.href)[1];
}

window.onload = function () {
    // 如果需要打码或者登陆
    // if (document.querySelector(".sufei-dialog.sufei-dialog-kissy") && document.querySelector(".sufei-dialog.sufei-dialog-kissy").style.display == 'block') {
    //     return;
    // }
    setTimeout(function () {
        scrapy();
    }, Math.random() * 2000);
}

function getdetail(fn) {
    $.get("https://api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/", {
        "v": "6.0",
        "type": "json",
        "dataType": "json",
        "appKey": "12574478",
        "t": "1471594755592",
        "ttid": "2013@taobao_h5_1.0.0",
        "api": "mtop.taobao.detail.getdetail",
        "data": JSON.stringify({"itemNumId": itemNumId, "exParams": JSON.stringify({"id": itemNumId})})
    }, function (response) {
        // 说明此次爬取有异常，隔两秒重新来一次
        if (!response.data.item) {
            setTimeout(function () {
                getdetail(fn);
            }, 2000);
        } else {
            fn(response);
        }
    });
}

function scrapy() {
    getdetail(function (response) {
        var models = document.querySelectorAll('.J_TSaleProp.tb-img li'), sizes = document.querySelectorAll('.J_Prop.J_TMySizeProp li');
        var stocks = [];

        var item = response.data.item || {};
        var seller = response.data.seller || {};

        if (response.data.skuBase && response.data.skuBase.props && response.data.skuBase.props.length == 2) {
            var props = response.data.skuBase.props; // 代号和中文的映射
            var skus = response.data.skuBase.skus;

            var sizeProps = props[0].values;
            var modelProps = props[1].values;

            var stockData = JSON.parse(response.data.apiStack[0].value);
            var sku2info = stockData.skuCore.sku2info;

            for (var i = 0; i < models.length; i++) {
                for (var j = 0; j < sizes.length; j++) {
                    var sizeCode = sizes[j].getAttribute('data-value'), modelCode = models[i].getAttribute('data-value');

                    var propPath = sizeCode + ';' + modelCode;

                    var skuId = getSkuId(skus, propPath);

                    // 断码的sku没有数据
                    if (getStockBySkuId(sku2info, skuId)) {
                        stocks.push({
                            stock: getStockBySkuId(sku2info, skuId),
                            size: getSizeByCode(sizeProps, sizeCode.split(':')[1]),
                            model: getModelByCode(modelProps, modelCode.split(':')[1])
                        });
                    }
                }
            }
        }

        chrome.runtime.sendMessage({
            "data": stocks,
            "title": item.title || "",
            "favcount": item.favcount || 0,
            "shopName": seller.shopName || ""
        });
    });
}

function getSkuId(skus, propPath) {
    for (var i = 0; i < skus.length; i++) {
        if (skus[i].propPath == propPath) {
            return skus[i].skuId;
        }
    }

    return null;
}

function getStockBySkuId(sku2info, skuId) {
    return sku2info[Number(skuId)] && sku2info[Number(skuId)].quantity;
}

function getModelByCode(modelProps, vid) {
    for (var i = 0; i < modelProps.length; i++) {
        if (modelProps[i].vid == vid) {
            return modelProps[i].name;
        }
    }
}

function getSizeByCode(sizeProps, vid) {
    for (var i = 0; i < sizeProps.length; i++) {
        if (sizeProps[i].vid == vid) {
            return sizeProps[i].name;
        }
    }
}